package com.outfit.boot.okhttp;

import lombok.extern.slf4j.Slf4j;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

/**
 * OkHttp自动配置
 *
 * @author ming
 * @date 2019-09-10 17:00
 * <p>company: 杭州行装网络技术有限公司</p>
 * <p>修改履历：</p>
 */
@Slf4j
@Configuration
@ConditionalOnClass(OkHttpService.class)
@ConditionalOnProperty(prefix = "outfit.okhttp", name = "max-idle-connections", matchIfMissing = true)
@EnableConfigurationProperties(OkHttpProperties.class)
public class OkHttpAutoConfiguration {

    private final OkHttpProperties okHttpProperties;

    public OkHttpAutoConfiguration(final OkHttpProperties okHttpProperties) {
        this.okHttpProperties = okHttpProperties;
    }

    @Bean
    @ConditionalOnMissingBean(OkHttpService.class)
    public OkHttpService okHttpService() {
        final OkHttpService okHttpService = new OkHttpService();
        okHttpService.initOkHttpClient(okHttpClient());
        return okHttpService;
    }

    @Bean
    public ConnectionPool pool() {
        return new ConnectionPool(
                okHttpProperties.getMaxIdleConnections(),
                okHttpProperties.getKeepAliveDuration(),
                TimeUnit.MILLISECONDS);
    }

    @Bean
    public OkHttpClient okHttpClient() {
        return new OkHttpClient.Builder()
                //.sslSocketFactory(sslSocketFactory(), x509TrustManager())
                //.retryOnConnectionFailure(false)
                .connectionPool(pool())
                .connectTimeout(okHttpProperties.getConnectTimeout(), TimeUnit.MILLISECONDS)
                .readTimeout(okHttpProperties.getReadTimeout(), TimeUnit.MILLISECONDS)
                .writeTimeout(okHttpProperties.getWriteTimeout(), TimeUnit.MILLISECONDS)
                .build();
    }

    @Bean
    public X509TrustManager x509TrustManager() {
        return new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
    }

    @Bean
    public SSLSocketFactory sslSocketFactory() {
        try {
            //信任任何链接
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            log.error("@Bean sslSocketFactory() Exception", e);
        }
        return null;
    }
}

